<?php
declare (strict_types = 1);

namespace app\controller\v1\admin;

use app\BaseController;
use app\common\Send;
use app\service\CaptchaService;
use app\service\MemberService;
use app\validate\Member as MemberValidate;
use think\App;
use think\Request;

class Member extends BaseController
{
    use Send;

    protected $memberService;
    protected $captchaService;
    public function __construct(App $app, MemberService $memberService,CaptchaService $captchaService)
    {
        parent::__construct($app);
        $this->memberService = $memberService;
        $this->captchaService = $captchaService;
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $data = $this->request->param();
        $result = $this->memberService->list($data);
        return self::success($result);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $data = $request->param();
        (new MemberValidate())->goCheck($data,'add');
        $result = $this->memberService->save($data);
        return self::success($result);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    public function money($id)
    {

        $data =  $this->request->param();
        $this->memberService->updateMoney($id, $data);
        return self::success("更新成功");
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data =  $request->param();
        (new MemberValidate())->goCheck($data,'update');
        $this->memberService->update($id, $data);
        return self::success("更新成功");
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $result = $this->memberService->delete($id);
        return self::success($result);
    }

    public function login(Request $request)
    {
        $data = $request->param();
        $result = $this->memberService->login($data);
        return self::success($result);
    }

    public function logout()
    {
//        // 从请求中获取令牌
//        $token = request()->_token;
//        // 调用用户服务的退出方法，并返回成功信息
//        $result = $this->memberService->logout($token);
//        return self::success($result, '退出成功!');
    }

    public function captcha()
    {
        $uid = 'captcha_' . uniqid('', true);

        $img = $this->captchaService->create($uid);

        return json([
            'image' => 'data:image/png;base64,'.base64_encode($img),
            'uid' => $uid
        ]);
    }

    public function children($id)
    {
        return self::success($this->memberService->children($id));
    }
}
